package com.cl.cloud.tenant.logDemo;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.cl.core.util.DateUtil;
import lombok.Data;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @description:
 * @author: liuzijian
 * @time: 2023-01-12 13:38
 */
@Data
public class AtomicOutPrint {

    private String logBasePath = "C:\\Users\\ADMIN\\Desktop\\印章测试";

    private String dateFormat = "yyyy-MM-dd HH:mm:ss.S";

    private String tag;

    private Long num = 1L;

    private Long 文件切分值 = 1000L;

    private Long 文件标记值 = 文件切分值;

    private ReentrantLock lock = new ReentrantLock();

    private Map<String, Object> map = new LinkedHashMap<>(1);

    private ExecutorService single = Executors.newSingleThreadExecutor();

    public AtomicOutPrint(String tag) {
        this.tag = tag;
    }

    public void print(String level) {

        try {
            lock.lock();
            Long id = num++;
            map.put("id", id);
            map.put("tag", tag);
            String str = StrUtil.format("{} [{}] {} - {}", DateUtil.format(new Date(), dateFormat), Thread.currentThread().getName(), level, JSONUtil.toJsonStr(map));
            single.submit(() -> {
                File file = null;
                if (文件标记值 < id) {
                    文件标记值 += 文件切分值;
                    file = new File(logBasePath + "\\" + tag + "-" + 文件标记值 + ".txt");
                } else {
                    file = new File(logBasePath + "\\" + tag + "-" + 文件标记值 + ".txt");
                }
                try (BufferedWriter bw = new BufferedWriter(new FileWriter(file, true))) {
                    bw.write(str);
                    bw.newLine();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
            System.out.println(str);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
